package com.qingdai.textmessageservice.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.qingdai.business.entities.CommonResult;
import com.qingdai.textmessageservice.service.TextMessageServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.rmi.ServerException;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;


//http://localhost:8101/QingDai/test/
@RestController
@RequestMapping("/test")
@CrossOrigin
public class TestController {
    @Resource
    private TextMessageServiceImpl textMessageService;
    @Resource
    private RedisTemplate redisTemplate;

    @GetMapping("/")
    public CommonResult test(@RequestParam(required = true) String phoneNumber) throws ServerException {
        //如果redis缓存中存在手机号的验证码，说明验证码还未过期，可继续使用
        Integer code = (Integer) redisTemplate.opsForValue().get(phoneNumber);
        if (code != null) {
            return new CommonResult<>(400, phoneNumber +"验证码还没有过期，可继续使用！");
        }
        Random random = new Random();
        code = random.nextInt(1000000);
        SendSmsResponse sendSmsResponse = textMessageService.sentLoginCode(phoneNumber, code);
        if (!Objects.equals(sendSmsResponse.getCode(), "OK")) {
            return new CommonResult<>(400, "发送验证码失败:" + sendSmsResponse.getMessage());
        }
        redisTemplate.opsForValue().set(phoneNumber, code, 30, TimeUnit.SECONDS);  //将验证码存到redis，设置30分钟过期
        return new CommonResult<>(200, "向" + phoneNumber + "发送验证码成功,验证码:" + code);
    }

    @GetMapping("/getCode")
    public CommonResult getCode(@RequestParam(required = true) String phoneNumber) {
        Integer code = (Integer) redisTemplate.opsForValue().get(phoneNumber);
        return new CommonResult<>(200, ":", code);
    }

}
